package master

import (
	"GoCrontab/crontab/common"
	"context"
	"github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/mvcc/mvccpb"
	"time"
)

type WorkerManager struct {
	client  *clientv3.Client
	kv      clientv3.KV
	lease   clientv3.Lease
	watcher clientv3.Watcher
}

var (
	GlobalWorkerManager *WorkerManager
)

func (w *WorkerManager) ListWorkers() (workerIpArr []string, err error) {

	// 这样定义的好处是默认值都为零值
	var (
		getResponse *clientv3.GetResponse
		workerIp    string
		kv          *mvccpb.KeyValue
	)

	if getResponse, err = w.kv.Get(context.TODO(), common.JOB_WORKER_DIR, clientv3.WithPrefix()); err != nil {
		return
	}

	for _, kv = range getResponse.Kvs {
		workerIp = common.ExtractWorkerIp(string(kv.Key))
		workerIpArr = append(workerIpArr, workerIp)
	}
	return

}

func InitWorkManager() (err error) {
	var (
		config  clientv3.Config
		client  *clientv3.Client
		kv      clientv3.KV
		lease   clientv3.Lease
		watcher clientv3.Watcher
	)
	config = clientv3.Config{
		Endpoints: GlobalConfig.EtcdEndPoints,
		Username:  GlobalConfig.EtcdUserName,
		Password:  GlobalConfig.EtcdPassword,
		//Millisecond 毫秒,1毫秒等于千分之一秒
		// MicroSecond 微秒,1微秒等于百万分之一秒
		DialTimeout: time.Duration(GlobalConfig.EtcdDialTimeout) * time.Millisecond,
	}

	if client, err = clientv3.New(config); err != nil {
		return
	}
	//得到KV和Lease的api子集
	kv = clientv3.NewKV(client)
	lease = clientv3.NewLease(client)
	watcher = clientv3.NewWatcher(client)

	GlobalWorkerManager = &WorkerManager{
		client:  client,
		kv:      kv,
		lease:   lease,
		watcher: watcher,
	}

	return
}
